import 'dart:io';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:path_provider/path_provider.dart';
import 'package:stacked/stacked.dart';
import 'package:stacked_services/stacked_services.dart';
import 'package:vista/shared/utils/url_open.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/features/challenge/viewmodels/theme_challenge_list_viewmodel.dart';
import 'package:vista/shared/models/challenge_submission.dart';
import 'package:vista/shared/constants/color.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/utils/widget_extension.dart';
import 'package:vista/shared/widgets/auth_gate_modal.dart';
import 'package:vista/shared/widgets/complain_bottom_sheet.dart';

/// 主题挑战列表页面
class ThemeChallengeListView extends StatelessWidget {
  const ThemeChallengeListView({super.key});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<ThemeChallengeListViewModel>.reactive(
      viewModelBuilder:
          () =>
              ThemeChallengeListViewModel(getIt.get(), getIt.get<AuthFocus>())
                ..initialize(),
      builder: (context, model, child) {
        return Scaffold(
          floatingActionButton: Container(
            width: 56.w,
            height: 56.w,
            decoration: BoxDecoration(
              color: ColorConstants.accentColor,
              shape: BoxShape.circle,
              border: Border.all(color: Colors.black, width: 1.w),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.2),
                  blurRadius: 8.w,
                  offset: Offset(0, 4.h),
                ),
              ],
            ),
            child: IconButton(
              onPressed: () => _showUploadDialog(context, model),
              icon: Icon(Icons.add, size: 28.w, color: Colors.white),
            ),
          ),
          floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
          body: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my-background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: Stack(
              children: [
                // 可滚动内容
                SafeArea(
                  top: false,
                  bottom: false,
                  child:
                      model.isBusy
                          ? const Center(child: CircularProgressIndicator())
                          : SingleChildScrollView(
                            child: [
                                  // 装饰图片和上传按钮（Stack布局）
                                  Stack(
                                    clipBehavior: Clip.none,
                                    children: [
                                      // 装饰图片（底层）
                                      Image.asset(
                                        'assets/images/challenge-decoration.png',
                                        width: double.infinity,
                                        fit: BoxFit.fitWidth,
                                      ),
                                      // 上传按钮（在装饰图片底部的z轴上方）
                                      Positioned(
                                        left: 14.w,
                                        right: 14.w,
                                        bottom: -64.h, // 按钮在装饰图片底部稍微下方
                                        child: _buildUploadButton(
                                          context,
                                          model,
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(height: 80.h),
                                  // 挑战列表（左右14.w间距）
                                  _buildSubmissionsGrid(
                                    context,
                                    model,
                                  ).frameHorizontal(14.w),
                                  SizedBox(height: 100.h), // 底部留白
                                ]
                                .verticalShot(
                                  crossAxisAlignment:
                                      CrossAxisAlignment.stretch,
                                )
                                .frameHorizontal(0),
                          ),
                ),
                // 固定返回按钮
                Positioned(
                  top: 0,
                  left: 0,
                  child: SafeArea(child: _buildHeader(context)),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建标题栏
  Widget _buildHeader(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 12.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => getIt.get<NavigationService>().back(),
            child: Image.asset(
              'assets/images/back.png',
              width: 24.w,
              height: 24.w,
              color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建上传按钮（仅显示，无点击事件）
  Widget _buildUploadButton(
    BuildContext context,
    ThemeChallengeListViewModel model,
  ) {
    return AspectRatio(
      aspectRatio: 347 / 129,
      child: Image.asset('assets/images/upload-button.png', fit: BoxFit.fill),
    );
  }

  /// 构建投稿列表网格
  Widget _buildSubmissionsGrid(
    BuildContext context,
    ThemeChallengeListViewModel model,
  ) {
    if (model.submissions.isEmpty) {
      return const SizedBox.shrink();
    }

    // 将投稿列表分成两列
    final List<Widget> rows = [];
    for (int i = 0; i < model.submissions.length; i += 2) {
      final List<Widget> rowItems = [];
      // 第一列
      if (i < model.submissions.length) {
        rowItems.add(
          Expanded(
            child: _buildSubmissionItem(context, model.submissions[i], model),
          ),
        );
      }
      // 间距
      if (i + 1 < model.submissions.length) {
        rowItems.add(SizedBox(width: 12.w));
        // 第二列
        rowItems.add(
          Expanded(
            child: _buildSubmissionItem(
              context,
              model.submissions[i + 1],
              model,
            ),
          ),
        );
      } else {
        // 如果只有一列，添加一个空的 Expanded 来保持布局
        rowItems.add(const Spacer());
      }

      rows.add(
        Row(crossAxisAlignment: CrossAxisAlignment.start, children: rowItems),
      );
      if (i + 2 < model.submissions.length) {
        rows.add(SizedBox(height: 12.h));
      }
    }

    return [
      ...rows,
    ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch);
  }

  /// 构建单个投稿项
  Widget _buildSubmissionItem(
    BuildContext context,
    ChallengeSubmission submission,
    ThemeChallengeListViewModel model,
  ) {
    final user = model.getUserById(submission.authorId);

    return GestureDetector(
      onTap: () {
        Navigator.of(context).pushNamed(
          '/challenge-detail',
          arguments: {'submissionId': submission.id},
        );
      },
      child: AspectRatio(
        aspectRatio: 167 / 237,
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8.r),
            border: Border.all(color: Colors.black, width: 2.w),
          ),

          child:
              [
                // 第一个 Row：蓝色背景，高度占 25/237
                Expanded(
                  flex: 25,
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.lightBlue,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(7.r),
                        topRight: Radius.circular(7.r),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        // 第一个装饰圆形（白色填充，黑色边框）
                        Container(
                          width: 16.w,
                          height: 16.w,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: Colors.white,
                            border: Border.all(color: Colors.black, width: 1.w),
                          ),
                        ),
                        SizedBox(width: 8.w),
                        // 第二个装饰圆形（浅粉色填充，黑色边框）
                        Container(
                          width: 16.w,
                          height: 16.w,
                          decoration: BoxDecoration(
                            shape: BoxShape.circle,
                            color: Colors.pink[200],
                            border: Border.all(color: Colors.black, width: 1.w),
                          ),
                        ),
                        SizedBox(width: 8.w),
                      ],
                    ),
                  ),
                ),
                // 第二个 Row：挑战图片，高度占 187/237
                Expanded(
                  flex: 187,
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      border: Border(
                        bottom: BorderSide(color: Colors.black, width: 1.w),
                      ),
                    ),
                    child: Padding(
                      padding: EdgeInsets.all(6.0.w),
                      child: Stack(
                        children: [
                          // 挑战图片（支持本地文件和asset）
                          _buildImage(submission.image),
                          // 发布者头像（左上角）
                          Positioned(
                            left: 8.w,
                            top: 8.h,
                            child: Container(
                              width: 32.w,
                              height: 32.w,
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                color: Colors.white,
                                border: Border.all(
                                  color: Colors.white,
                                  width: 1.w,
                                ),
                                image:
                                    user?.avatar != null
                                        ? DecorationImage(
                                          image: AssetImage(user!.avatar!),
                                          fit: BoxFit.cover,
                                        )
                                        : null,
                              ),
                              child:
                                  user?.avatar == null
                                      ? Icon(
                                        Icons.person,
                                        size: 20.w,
                                        color: Colors.grey,
                                      )
                                      : null,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
                // 第三个 Row：底部操作栏，高度占 25/237
                Expanded(
                  flex: 25,
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(8.r),
                        bottomRight: Radius.circular(8.r),
                      ),
                    ),
                    padding: EdgeInsets.symmetric(horizontal: 8.w),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        // 举报 icon
                        GestureDetector(
                          onTap: () async {
                            await ComplainHelper.unveil(
                              context,
                              onComplain: (reason) async {
                                // 举报成功后删除挑战
                                await model.deleteSubmission(submission.id);
                                if (context.mounted) {
                                  FlashNotifier.flashSuccess(
                                    'Report submitted successfully',
                                  );
                                }
                              },
                            );
                          },
                          child: Image.asset(
                            'assets/images/report.png',
                            width: 18.w,
                            height: 18.w,
                          ),
                        ),
                        const Spacer(),
                        // 点赞按钮和点赞数
                        GestureDetector(
                          onTap: () async {
                            final currentUser =
                                await getIt<AuthFocus>().getCurrentUser();
                            if (currentUser == null) {
                              final result = await showDialog<bool>(
                                context: context,
                                builder: (context) => const AuthGateModal(),
                              );
                              if (result == true) {
                                Navigator.of(context).pushNamed('/login');
                              }
                              return;
                            }
                            await model.toggleLike(submission.id);
                          },
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(
                                model.isLiked(submission.id)
                                    ? Icons.favorite
                                    : Icons.favorite_border,
                                size: 18.w,
                                color:
                                    model.isLiked(submission.id)
                                        ? Colors.red
                                        : Colors.black87,
                              ),
                              SizedBox(width: 4.w),
                              Text(
                                '${model.getLikeCount(submission.id)}',
                                style: TextStyle(
                                  fontSize: 12.sp,
                                  color: Colors.black87,
                                  fontWeight: FontWeight.w600,
                                ),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(width: 12.w),
                        // 访问 icon 和访问数
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Image.asset(
                              'assets/images/eye.png',
                              width: 20.w,
                              height: 20.h,
                              fit: BoxFit.contain,
                              color: Colors.black87,
                            ),
                            SizedBox(width: 4.w),
                            Text(
                              '${submission.viewCount}',
                              style: TextStyle(
                                fontSize: 12.sp,
                                color: Colors.black87,
                                fontWeight: FontWeight.w600,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ].verticalShot(),
        ),
      ),
    );
  }

  /// 显示上传对话框
  Future<void> _showUploadDialog(
    BuildContext context,
    ThemeChallengeListViewModel model,
  ) async {
    // 检查是否登录
    final currentUser = await getIt<AuthFocus>().getCurrentUser();
    if (currentUser == null) {
      final result = await showDialog<bool>(
        context: context,
        builder: (context) => const AuthGateModal(),
      );
      if (result == true) {
        Navigator.of(context).pushNamed('/login');
      }
      return;
    }

    // 显示上传弹窗
    await showDialog(
      context: context,
      builder:
          (context) => _UploadDialog(
            onPublish: (imagePath) async {
              if (imagePath != null) {
                await model.submitSubmission(imagePath);
                if (context.mounted) {
                  Navigator.of(context).pop();
                  FlashNotifier.flashSuccess(
                    'Submission uploaded successfully',
                  );
                }
              } else {
                if (context.mounted) {
                  FlashNotifier.flashError('Please select an image first');
                }
              }
            },
            onCopyImageToLocal: _copyImageToLocal,
          ),
    );
  }

  /// 构建图片 Widget（支持本地文件和asset）
  Widget _buildImage(String imagePath) {
    // 判断是本地文件路径还是asset路径
    if (imagePath.startsWith('/') || imagePath.startsWith('file://')) {
      // 本地文件路径
      return Image.file(
        File(imagePath),
        width: double.infinity,
        height: double.infinity,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            color: Colors.grey[300],
            child: Icon(Icons.broken_image, size: 40.w, color: Colors.grey),
          );
        },
      );
    } else {
      // asset路径
      return Image.asset(
        imagePath,
        width: double.infinity,
        height: double.infinity,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            color: Colors.grey[300],
            child: Icon(Icons.broken_image, size: 40.w, color: Colors.grey),
          );
        },
      );
    }
  }

  /// 将图片复制到本地目录
  Future<String?> _copyImageToLocal(AssetEntity asset) async {
    try {
      // 获取应用文档目录
      final directory = await getApplicationDocumentsDirectory();
      final imagesDir = Directory('${directory.path}/challenge_images');

      // 如果目录不存在，创建它
      if (!await imagesDir.exists()) {
        await imagesDir.create(recursive: true);
      }

      // 生成唯一的文件名
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final fileName = 'challenge_$timestamp.jpg';
      final filePath = '${imagesDir.path}/$fileName';

      // 读取图片数据
      final file = await asset.file;
      if (file == null) {
        return null;
      }

      // 复制文件到本地目录
      final localFile = File(filePath);
      await file.copy(localFile.path);

      // 返回本地路径（用于存储和显示）
      return localFile.path;
    } catch (e) {
      return null;
    }
  }
}

/// 上传挑战弹窗
class _UploadDialog extends StatefulWidget {
  final Future<String?> Function(AssetEntity) onCopyImageToLocal;
  final Future<void> Function(String?) onPublish;

  const _UploadDialog({
    required this.onCopyImageToLocal,
    required this.onPublish,
  });

  @override
  State<_UploadDialog> createState() => _UploadDialogState();
}

class _UploadDialogState extends State<_UploadDialog> {
  String? _selectedImagePath;
  bool _isUploading = false;

  /// 选择图片
  Future<void> _selectImage() async {
    try {
      final List<AssetEntity>? selectedAssets = await AssetPicker.pickAssets(
        context,
        pickerConfig: const AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
        ),
      );

      if (selectedAssets == null || selectedAssets.isEmpty) {
        return; // 用户取消了选择
      }

      final asset = selectedAssets.first;

      // 将图片复制到本地目录
      final localPath = await widget.onCopyImageToLocal(asset);

      if (localPath != null && mounted) {
        setState(() {
          _selectedImagePath = localPath;
        });
      } else {
        if (mounted) {
          FlashNotifier.flashError('Failed to save image');
        }
      }
    } catch (e) {
      if (mounted) {
        FlashNotifier.flashError('Error selecting image: $e');
      }
    }
  }

  /// 发布
  Future<void> _publish() async {
    if (_selectedImagePath == null) {
      FlashNotifier.flashError('Please select an image first');
      return;
    }

    setState(() {
      _isUploading = true;
    });

    try {
      await widget.onPublish(_selectedImagePath);
    } finally {
      if (mounted) {
        setState(() {
          _isUploading = false;
        });
      }
    }
  }

  // 从 my-background.png 提取的颜色
  static const Color _primaryColor = Color(0xFF4A5568);
  static const Color _accentColor = Color(0xFFFFA680);

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.r)),
      insetPadding: EdgeInsets.symmetric(horizontal: 40.w, vertical: 80.h),
      child: Container(
        constraints: BoxConstraints(maxWidth: 320.w, minWidth: 280.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20.r),
          gradient: LinearGradient(
            begin: Alignment(1.00, 2.84),
            end: Alignment(0.00, 2.84),
            colors: [const Color(0xFFFFA680), const Color(0xFFFFEBE6)],
          ),
        ),
        child: [
              // 标题
              Text(
                'Upload Challenge',
                style: TextStyle(
                  fontSize: 22.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.black87,
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 24.h),
              // 图片选择容器
              GestureDetector(
                onTap: _selectImage,
                child: Container(
                  width: double.infinity,
                  height: 180.h,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(12.r),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withOpacity(0.05),
                        blurRadius: 8.w,
                        offset: Offset(0, 2.h),
                      ),
                    ],
                  ),
                  child:
                      _selectedImagePath != null
                          ? ClipRRect(
                            borderRadius: BorderRadius.circular(12.r),
                            child: Image.file(
                              File(_selectedImagePath!),
                              width: double.infinity,
                              height: double.infinity,
                              fit: BoxFit.cover,
                              errorBuilder: (context, error, stackTrace) {
                                return _buildPlaceholder();
                              },
                            ),
                          )
                          : _buildPlaceholder(),
                ),
              ),
              SizedBox(height: 16.h),
              // EULA 链接
              GestureDetector(
                onTap: UrlOpen.openEulaUrl,
                child: Text(
                  'EULA',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: _accentColor,
                    decoration: TextDecoration.underline,
                  ),
                  textAlign: TextAlign.center,
                ),
              ),
              SizedBox(height: 24.h),
              // 按钮组
              [
                    // 取消按钮
                    Expanded(
                      child: OutlinedButton(
                        onPressed: () => Navigator.of(context).pop(),
                        style: OutlinedButton.styleFrom(
                          padding: EdgeInsets.symmetric(vertical: 14.h),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10.r),
                          ),
                          side: BorderSide(color: Colors.grey[300]!),
                        ),
                        child: Text(
                          'Cancel',
                          style: TextStyle(
                            fontSize: 15.sp,
                            color: Colors.grey[700],
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 12.w),
                    // 发布按钮
                    Expanded(
                      child: ElevatedButton(
                        onPressed: _isUploading ? null : _publish,
                        style: ElevatedButton.styleFrom(
                          padding: EdgeInsets.symmetric(vertical: 14.h),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10.r),
                          ),
                          backgroundColor: _accentColor,
                          foregroundColor: Colors.white,
                          elevation: 0,
                          disabledBackgroundColor: Colors.grey[300],
                        ),
                        child:
                            _isUploading
                                ? SizedBox(
                                  width: 20.w,
                                  height: 20.w,
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                    valueColor: AlwaysStoppedAnimation<Color>(
                                      Colors.white,
                                    ),
                                  ),
                                )
                                : Text(
                                  'Publish',
                                  style: TextStyle(
                                    fontSize: 15.sp,
                                    fontWeight: FontWeight.w600,
                                  ),
                                ),
                      ),
                    ),
                  ]
                  .horizontalGallery(
                    mainAxisAlignment: MainAxisAlignment.center,
                  )
                  .frameHorizontal(0),
            ]
            .verticalShot(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
            )
            .frameAll(32.w),
      ),
    );
  }

  /// 构建占位符
  Widget _buildPlaceholder() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 56.w,
          height: 56.w,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                _accentColor.withOpacity(0.2),
                _primaryColor.withOpacity(0.1),
              ],
            ),
          ),
          child: Icon(
            Icons.cloud_upload_rounded,
            size: 28.w,
            color: _accentColor,
          ),
        ),
        SizedBox(height: 12.h),
        Text(
          'Tap to select image',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[600],
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }
}
